<template>
   <div style="padding: 20px;">
        <div style="display: flex; margin-bottom: 20px;" >
            <el-input class="search-input" placeholder="账号" v-model="searchLoginAct"/>
            <el-input class="search-input" placeholder="姓名" v-model="searchName"/>
            <el-input class="search-input" placeholder="手机号" v-model="searchPhone"/>
            <el-button type="info"  @click="search(1)">搜索</el-button>
            <el-button type="primary" @click="addUser">新增用户</el-button>
            <el-button type="danger"  @click="batchDeleteByIds">批量删除</el-button>
        </div>
    <el-table 
        :data="userList" 
        style="width: 100%" 
        border
        table-layout="auto"
        @selection-change="handleSelectionChange"
    >
        <el-table-column type="selection"/>
        <el-table-column prop="id" label="序号"  />
        <el-table-column prop="loginAct" label="账号" />
        <el-table-column prop="name" label="姓名"  />
        <el-table-column prop="phone" label="手机" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" >
            <template #default="scope">
                <el-button type="primary" plain @click="userDetail(scope.row)">
                    详情
                </el-button>
                <el-button  type="success"  plain @click="editUser(scope.row)">
                    编辑
                </el-button>
                <el-button  type="danger"  plain @click="delUser(scope.row)">
                    删除
                </el-button>
            </template>
        </el-table-column> 
    </el-table>
    <!-- 分页 -->
    <div style="margin-top: 20px;">
        <el-pagination 
            background 
            layout="prev, pager, next" 
            :total="page.total"
            :page-size="page.pageSize"
            @current-change="currentChange" 
        />
    </div>
    <!-- 新增和编辑用户的提示框 -->
    <el-dialog
        v-model="dialogVisible"
        title="用户信息"
        width="500"
    >
    <div>
        <el-form
            ref="formRef"
            style="max-width: 600px"
            :model="formUser"
            label-width="auto"
            :rules="formRules"
        >
            <el-form-item label="账号" prop="loginAct">
                <el-input v-model="formUser.loginAct"  autocomplete="off" />
            </el-form-item>
            <el-form-item label="密码" prop="loginPwd" v-if="addOrUpdateValue == 'add'">
                <el-input v-model="formUser.loginPwd" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="姓名" prop="name">
                <el-input v-model="formUser.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="手机" prop="phone">
                <el-input v-model="formUser.phone"  autocomplete="off" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="formUser.email"  autocomplete="off" />
            </el-form-item>
            <el-form-item label="账号未过期" prop="accountNoExpired">
                <el-select v-model="formUser.accountNoExpired" placeholder="请选择">
                    <el-option label="是" value="1" />
                    <el-option label="否" value="0" />
                </el-select>
            </el-form-item>
            <el-form-item label="密码未过期" prop="credentialsNoExpired">
                <el-select v-model="formUser.credentialsNoExpired" placeholder="请选择">
                    <el-option label="是" value="1" />
                    <el-option label="否" value="0" />
                </el-select>
            </el-form-item>
            <el-form-item label="账号未锁定" prop="accountNoLocked">
                <el-select v-model="formUser.accountNoLocked" placeholder="请选择">
                    <el-option label="是" value="1" />
                    <el-option label="否" value="0" />
                </el-select>
            </el-form-item>
            <el-form-item label="账号是否启用" prop="accountEnabled">
                <el-select v-model="formUser.accountEnabled" placeholder="请选择">
                    <el-option label="是" value="1" />
                    <el-option label="否" value="0" />
                </el-select>
            </el-form-item>
        </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addOrUpdate(formRef)">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
   </div>
</template>
<script lang="ts" setup name="UserManage">
import { baseService } from '@/utils/httpReqest';
import { onMounted, ref, reactive } from 'vue';
import User from '@/hooks/user';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import router from '@/router';
let userList = ref<Array<User>>([]);
let searchLoginAct = ref("");
let searchName = ref("");
let searchPhone = ref("");
let selectIds: any[] = [];
let formRef = ref<FormInstance>();
let addOrUpdateValue = ref('');
let page = reactive({
    pageSize: 8, //单页记录数
    total: 0,
    currentPage: 1,
})
let dialogVisible = ref(false);
let formUser = reactive(new User());
// 搜索用户信息
let search = (currentPage = 1) => {
    baseService.doGet("/user/searchUser", {
        searchLoginAct: searchLoginAct.value,
        searchName: searchName.value,
        searchPhone: searchPhone.value,
        currentPage: currentPage

    }).then((res: any) => {
        if (res.code == 200) {
            userList.value = res.data.data
            page.total = res.data.total;
        }
    })
}
onMounted(() => {
    search(1);
})
let currentChange = (number: number) => {
    page.currentPage = number;
    search(number);
}
let handleSelectionChange = (userArray: any[]) => {
    selectIds = []
    // console.log(userArray[0]);
    userArray.forEach((user) => {
        selectIds.push(user.id)
    })
}
let batchDeleteByIds = () => {
    ElMessageBox.confirm(
        '确定删除吗？',
        '批量删除',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        if (selectIds.length < 1) {
            ElMessage.error("请选择用户")
        } else {
            baseService.doDelete("/user/batchDeleteUserByIds", selectIds)
                .then((res: any) => {
                    if (res.code == 200) {
                        ElMessage.success("删除成功")
                        search(page.currentPage)
                    } else {
                        ElMessage.error("删除失败，请联系管理后台人员")
                    }
                })
        }
    })
}
let userDetail = (row: User) => {
    router.push(`detail/${row.id}`)
}


let formRules = reactive<FormRules<typeof formUser>>({
    loginAct: [
        { required: true, message: '账号不能为空', trigger: 'blur' },
    ],
    loginPwd: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
        { min: 6, max: 12, message: "最低6位", trigger: 'blur' }
    ],
    name: [{ required: true, message: '姓名不能为空', trigger: 'blur' },],
    phone: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
    ],
    email: [
        { required: true, message: '邮箱不能为空', trigger: 'blur' },
        { pattern: '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', message: "请输入正确格式的邮箱", trigger: "blur" }
    ],
    accountNoExpired: [{ required: true, message: '选择项不能为空', trigger: 'blur' }],
    credentialsNoExpired: [{ required: true, message: '选择项不能为空', trigger: 'blur' }],
    accountNoLocked: [{ required: true, message: '选择项不能为空', trigger: 'blur' }],
    accountEnabled: [{ required: true, message: '选择项不能为空', trigger: 'blur' }]
})

let addUser = () => {
    addOrUpdateValue.value = "add"
    for (let key in formUser) {
        formUser[key as keyof User] = ""
    }
    if (formRef.value) {
        formRef.value.resetFields();
    }
    dialogVisible.value = true;
}
let editUser = (row: User) => {
     addOrUpdateValue.value = "edit"
    for (const key in formUser) {
       formUser[key as keyof User] = row[key as keyof User]+"";
    }
    dialogVisible.value = true;
}
let addOrUpdate = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            dialogVisible.value = false;
            if ("add" == addOrUpdateValue.value) {
                // 增加用户
                baseService.doPost("/user/addUser", formUser).then((res: any) => {
                    if (res.code == 200) {
                        ElMessage.success("添加成功")
                    } else {
                        ElMessage.error("添加失败")
                    }
                    search(page.currentPage);
                })

            } else {
                // 修改用户
                baseService.doPut("/user/updateUser", formUser).then((res: any) => {
                    if (res.code == 200) {
                        ElMessage.success("更新成功")
                    } else {
                        ElMessage.error("更新失败")
                    }
                    search(page.currentPage);
                })
            }
        } else {
            console.log('提交失败!')
        }
    })
}
let delUser = (user:User) => {
    ElMessageBox.confirm(
        `确定删除${user.loginAct}吗？`,
        '删除用户',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        baseService.doDelete(`user/deleteUser/${user.id}`).then((res:any) => {
        if (res.code == 200) {
            ElMessage.success("删除成功")
        } else {
            ElMessage.error(res.msg)
        }
        search(page.currentPage);
    })
    })
 
}
</script>
<style scoped>
.search-input {
    display: inline;
    margin-right: 7px;
    width: 180px;
}
</style>